import React, {
	Component
} from 'react';
import {
	observable,
	action,
	computed,
} from 'mobx';
import {
	Tools,
	Bubble,
	Toast,
	Modal,
} from "weaver-mobile";
import {isEmpty} from "lodash";
import { RouteLayout } from 'weaver-mobile-page';
import * as api from '../../apis/payrollDetail.js';
const getLabel = Tools.getLabel;
const prompt = Modal.prompt;

class HrmPayrollDetail{
	@observable notAuth = false;
	@observable imgId = '';
	@observable displayType = '0';

	@observable data = [];
	@observable payrollDetail = {};

	@observable isNeedSecondPwdVerify = true;

	@observable authloading = true;
	@observable pageloading = true;

	@computed get hasPayrollDetail(){
		return !isEmpty(this.payrollDetail)
	}

	@computed get longTxtColIndexs(){
		const indexs = [];

		this.data.forEach(item => {
			item.forEach( (val,index) => {
				if (val.length > 15) {
					indexs.push(index)
				}
			})
		})

		return [...new Set(indexs )];
	}

	@computed get cols(){
		return this.data[0].length;
	}

	@computed get colDatas() {
		const arr = [];

		this.data.forEach((item, index) => {
			if (index === 0) {
			} else {
				item.forEach((val, index) => {
					if (!arr[index]) {
						arr.push([]);
					}
					arr[index].push(val)
				})
			}
		});

		return arr;
	}

	@computed get rowDatas(){
		const arr = [];

		for(let i =0;i < this.data.length; i++){
			arr.push([]);
		}

		this.data.forEach((item,oindex)=>{
			item.forEach((val,index)=>{
				if (index > 0) {
					arr[oindex].push(val);
				}
			} )
		});

		return arr;
	}

	init = () => {
		this.loadingToast();

		this.getPayrollDetail().then(()=>{
			this.hideToast();
		});
	}

	getPayrollDetail = () => {
		return new Promise( (resolve,reject) => {
			api.readRecord(this.params).then(datas => {
				const {data,status} = datas;
				this.notAuth = (status == '0');
				if (status === '1' || status == '0') {
					this.payrollDetail = data;

					data && Object.keys(data).forEach(key => {
						if (key === 'data') {
							this[key] = JSON.parse(data[key]);
						}else{
							this[key] = data[key];
						}
					})

					resolve();
				}else{
					datas.message && Bubble.warning(datas.message);
					reject();
				}

				this.pageloading = false;
				
			})
		} )
	}

	@action getVerifyInfo = () => {
		//外部用户，不需要单点登录
		const { em_no_login } = this.params;
		if (em_no_login == "1") {
			this.isNeedSecondPwdVerify = false
			this.getCpUser(this.init, () => {this.notAuth = true;})
			this.authloading = false;
		}else{
			Promise.all([api.getSecondaryPasswordForm(), api.isNeedSecondPwdVerify()]).then(datas => {
				datas.forEach((item, index) => {
					if (index === 0) {
						this.isNeedSecondPwdSet = !item.settedSecondPassword
					}
					if (index === 1) {
						this.isNeedSecondPwdVerify = item.isNeedSecondPwdVerify;

						if(item.isNeedSecondPwdVerify){
							this.showPrompt()
						}else{
							this.init();
						}
					}
				})

				this.authloading = false;
			})
		}

		
	}

	getCpUser  = (success,fail) => {
		if(window.em && window.em.checkJsApi("getCpUser")){
			window.em.getCpUser({
				outSysId: window.localStorage.emobile_ec_id,
				success:res => {
					const wechatid = this.params.wechatid
					if ( wechatid == res.outsysUserId || wechatid == res.openUserId) {
						success&& success();
					}else{
						fail&& fail();
					}
				},
				fail:res => {
					fail&& fail();
					Bubble.error(JSON.stringify(res)) ;
				}
			});
		}else{
			fail();
		}
	}

	showPrompt = () => {
		const promptInstance = prompt(
			getLabel(501195, '身份验证'),
			(this.isNeedSecondPwdSet && <div className='hrm-id-verify'>
				{`${getLabel(508043,'您还未设置二次验证密码')}, ${getLabel(508044,'点击')} `}
				<span onClick={() => {
					if (window.em && window.em.checkJsApi('openLink')) {
						 window.em.openLink({
							url: `/spa/hrm/static4mobile/index.html#/secondaryVerification`,
					        openType: 2,
					        sysId: window.localStorage.emobile_ec_id
						});
					}else{
						window.location.href = "/spa/hrm/static4mobile/index.html#/secondaryVerification"
						promptInstance.close && promptInstance.close();
					}
				}}>{getLabel(30747,'设置')}</span>
			</div>), [{
				text: getLabel(201, '取消')
			}, {
				text: getLabel(826, '确定'),
				onPress: this.verify
			}],
			'secure-text',
			'', [getLabel(501201, '请输入二次验证密码')]
		)
	}

	verify = (text) => {
		return new Promise( (resolve,reject) => {
			if (text === '') {
				Bubble.warning(getLabel(501201,'请输入二次验证密码'));
				reject();
				return ;
			}

			this.checkSecondPassword(text).then(()=>{
				this.isNeedSecondPwdVerify = false;
				this.init();
				
				resolve();
			} ).catch(() => {
				reject();
			})
		} )
	}

	checkSecondPassword = (text) => {
		return new Promise((resolve, reject) => {
			api.checkSecondPassword({
				secondpassword: text
			}).then(datas => {
				const {
					status,
					message,
				} = datas;

				if (status === '1') {
					resolve();
				} else {
					Bubble.warning(message);
					reject();
				}
			});
		});
	}

	setTargetId = (params) => {
		this.params = params;
	}

	reset = () => {
		this.authloading = true;
		this.pageloading = true;
	}

	loadingToast = () => {
		Toast.loading('', 0);
	}

	hideToast = () => {
		Toast.hide()
	}

	@observable confirm = "";
	@observable confirmdata = "";
	@observable remark = "";
	@observable remarkdata = "";
	@observable layout = new RouteLayout.Store({ route: '/payrollDetail', id: 'feedback' });

	getNoLoginid = () => {
		const params = {};
		const {em_no_login,wechatid,notLoginid} = this.params;
		if (em_no_login == '1') {
			Object.assign(params,{
				wechatid,
				notLoginid,
			})
		}
		return params
	}

	confirmRecord = () => {
		const params = { targetId: this.params.targetId,...this.getNoLoginid() };
		
	    api.confirmRecord(params).then(res => {
	        if (res.status == "1") {
	            Bubble.success(getLabel('524279','确定成功') );
	            this.getPayrollDetail();
	        } else {
	            Bubble.error(res.message);
	        }
	    })
	}

	feedback = (history) => {
		this.remarkTxt = "";
		 history.push(this.layout.path)
	}

	submit = (history) => {
		if (!this.remarkTxt) {
			Bubble.warning(`'反馈信息‘ 必填!`)
			return 
		}
		const params = {targetId: this.params.targetId, remark: this.remarkTxt,...this.getNoLoginid()}
		
		api.feedback(params).then(res => {
			if (res.status == "1") {
				Bubble.success(getLabel('524280','信息已反馈') );
				history.go(-1);
				this.getPayrollDetail();
			}else{
				Bubble.error(res.message);
			}
		})
		
	}

	handleTextareaChange = (val) => {
		this.remarkTxt = val;
	}


}

export const hrmPayrollDetailStore = new HrmPayrollDetail();